Purpose: Some basic programming exercises for becoming familiar with the Java programming tools and writing some simple programs.
Goal: Complete as many of the exercise questions as you can. If you are keeping up, you need to do at least the core questions. The additional questions are more challenging and are designed to stretch the more confident programmers. Don't worry if you can't do them now, but be prepared to come back and try them later on.
Marking: All questions are binary marked.
To get a question marked, print out the program you have written and a cover
sheet from the 1b11 web page. Fill in the cover sheet and attach it to the
program listing, then take the work to your lab group demonstrator for marking.
The demonstrator may want to see a demonstration of your program running. An
answer can be submitted as many times as you like, until it is
satisfactory.
All printing should be done on the line printer (a4lp) - don't
use up your laser printer quota!
NOTE: You must keep all marked work as it forms a record of your progress. At the end of the course you are required to re-submit all work.
For these exercises you will be working with two kinds of program. The first kind represents the very simplest form of Java programs. These programs always have this basic structure:
class ProgramName { public static void main(String[] args) { // Write your program statements here. } }
The lines of source code in bold represent the basic infrastructure that must be included in any program for it to be syntactically correct. For now you will have to take these for granted and simply type them in. As the course progresses, their true purpose and meaning will be explained.
Source code is typed into the computer using an editor — you should be using emacs — and then saved to a file. The name ProgramName is effectively the name of the program (although, as we shall see, it is really the name of something called a class), and the source should be saved into a file of the same name with '.java' appended - ProgramName.java. When you write programs you should substitute a different name for each program (so, don't call every one ProgramName, it is just an example name!). The name should try to describe what the program does. It should also start with a capital letter and not include any spaces or punctuation marks.
All programs, however simple, should start with two lines of comments, the first stating who wrote the program and the date, the second giving a brief explanation of what the program does:
// Written by A.Person 2/10/00 // This program displays some useful information class ProgramName { public static void main(String[] args) { // Write your program statements here. } }
The code you write for your program should be substituted for the comment line '// Write your program statements here'. A statement is the term used to denote one complete action or command forming part of your program.
A program is compiled using the javac command:
javac ProgramName.java
and executed using the java command:
java ProgramName
When the compilation is successful a .class file is created and will appear in your directory (for example, ProgramName.class). This file contains the code to execute your program so don't delete it!
The second kind of program you will be writing is for displaying simple drawings created from lines and other shapes. Like the simplest programs described above, drawing programs requires some predefined infrastructure, which you will have to take as given for the time being. You need to locate the comments indicating where changes should be made and substitute your code as necessary.
The code of the simple drawing program is as follows (the fixed infrastructure code is in bold):
// Written by A.Person, 2/10/00 // This program draws a simple picture // Use code from the Java libraries
import java.awt.* ; import java.awt.event.* ;
// This program will be called Drawing and needs // to stored in a file called Drawing.java. // To create your own program with a different name, // change *all* the occurrences of Drawing to the new // name. Save the program to a new file named using the // new name with .java appended. class Drawing extends Frame { static class DrawArea extends Panel { // This part of the program does the actual drawing. public void paint(Graphics g) { // You add/change the statements here to draw // the picture you want. g.drawLine(0,0,300,300) ; }
// This part of the program makes sure that // the window drawing area ends up being the // right size. You don't need to change this. public Dimension getPreferredSize() { return new Dimension(WIDTH,HEIGHT) ; }
// These set the size of the drawing area. // By default this will be 300 by 300 pixels. // Change the sizes to suit what you need. private int WIDTH = 300 ; private int HEIGHT = 300 ; }
// Create a new window frame. public Drawing(String name) { super(name) ; } // This will terminate the program when the user // wants to quit. private static void quit() { System.exit(0) ; }
// This part of the program sets everything up // and displays the drawing window. public static void main(String[] args) { // Create the window frame with the label // "My Drawing". Change the text to change // the label. Drawing frame = new Drawing("My Drawing") ; // Create the contents of the frame. The top (or Center) // part is the drawing area. The bottom (or South) strip // holds a quit button. DrawArea drawing = new DrawArea() ; Panel buttonPanel = new Panel() ; buttonPanel.setLayout(new BorderLayout()) ; Button quitButton = new Button("Quit") ; buttonPanel.add("Center",quitButton) ; frame.setLayout(new BorderLayout()) ; frame.add("Center",drawing) ; frame.add("South",buttonPanel) ; // The event listeners are set up here to enable the // program to respond to events. quitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { quit() ; } }) ; frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { quit() ; } }) ; frame.pack() ; frame.setVisible(true) ; } }
To run this program, type in the program code and store it into a file called Drawing.java (or if you are paying attention use cut and paste from the web page version of these exercises to avoid typing in all the code!) Compile the code using the command:
javac Drawing.java
and then run the program using:
java Drawing
A window like this should appear on the screen:
The window contains a line drawn by the statement:
g.drawLine(0,0,300,300) ;
In technical terms this means call the method drawLine for the graphics object g, specifying the end points of the line as 0,0 and 300,300. The full meaning of this will become clear in time but it should be obvious that drawLine means draw a line using the start and end points specified. The task of actually drawing the line is performed by the graphics object, without you needing to know how that actually happens. The punctuation (dot, commas and semi-colon) must be present - when you write a drawing program try leaving some of them out and see what happens!
Drawing lines works much the same way as drawing on a piece of graph paper. Notice that the diagonal line slopes from top to bottom, left to right. The co-ordinate of the top left of the window is (0,0), while the co-ordinate at the bottom right is (300,300). Based on this you should be able to work out how to draw a line in any position (just like drawing on graph paper, except you have to remember that (0,0) is at top left not bottom left).
This window will remain on the screen while the program is still running. To stop the program click the Quit button at the bottom of the window .Clicking the button generates an event that the program responds to and it will stop running. Alternatively, the program will stop if you click the window frame close control (providing the window manager of the operating system you are using supplies one). Programs can also be stopped by typing Ctrl-C in the terminal window.
If you read the comment lines in the program carefully you will see the things that you can change. In particular, look for the part where it says
// You add/change the statements here to draw // the picture you want.
To draw something different you add or edit statements here. For example, to draw a line from bottom left to top right change the statement:
g.drawLine(0,0,300,300) ;
to:
g.drawLine(0,300,300,0) ;
What else can be drawn? The following is a list of some of the possibilities:
If you want know more, visit the online Java documentation and look for class Graphics. On the local CS web this can be seen at: http://www.cs.ucl.ac.uk/teaching/java/jdk1.2/docs/index.html. At first sight this documentation will appear complex and unfriendly. But don't be put off, over time you will make sense of it and find it becomes an invaluable source of information.
Example 1. Write a drawing program to display an octagon.
Problem solving steps:
1. Do you understand the question? Study it to make sure you understand what you are required to do. Don't waste time answering the wrong question!
2. How many sides does an octagon have? Answer: 8.
3. To draw an octagon you need to make two decisions:
i) How
large it will be, and hence the length of each side.
ii) The position it will
be drawn at.
4. Then you need to work out the coordinates of where each side of
the octagon starts and ends. Good old trigonometry comes into play to determine
the coordinates. But remember that an octagon is a symmetric shape so only a
small number of coordinates need to be calculated the hard way, the rest are
just offsets from those already calculated. Always look for short-cuts!
(It
would be a good idea to double check you can work out the coordinates yourself —
have I got those in the example code correct?)
5. Copy the drawing program code, do the renaming as described and write 8 drawLine statements to display the lines using the coordinates just calculated. Don't forget to save the code in a properly named file.
6. Compile the program, fixing any compilation errors by repeated editing and re-compilation.
7. Run the program and check it displays the correct result:
8. If the result is not correct then double check everything. If there is no obvious problem, go back to step 1 and work you way through the steps again. Question and check everything. All too often the thing you think must be correct is wrong!
Don't worry if a program doesn't work first time - they never do! An important part of programming is to persevere. Eventually the problems will be sorted out but it can take time. This is normal.
The statements to draw the octagon are:
g.drawLine(60,25,110,25) ; g.drawLine(110,25,145,60) ; g.drawLine(145,60,145,110) ; g.drawLine(145,110,110,145) ; g.drawLine(110,145,60,145) ; g.drawLine(60,145,25,110) ; g.drawLine(25,110,25,60) ; g.drawLine(25,60,60,25) ;
Notice that each statement is on a separate line and ends with a semi-colon.
The text of a program should always be presented neatly and made as readable as possible. Program code is primarily read by people (you!) so make sure it communicates effectively:
If you submit messy code, you won't get a binary mark tick and will have to tidy it up before re-submitting.
Q1.1 Type in the following Java program, compile it and then run it.
// Your name and date // This program outputs a simple message. class MyProgram { public static void main(String[] args) { System.out.println("This is my first Java program") ; System.out.println("It WORKS!!") ; } }
The line containing System.out.println is referred to as an output statement, and is used to display text on the computer screen. Again you will have to take as given the structure of an output statement but you can edit the text between the double quotes to output anything you like.
Hints: Use two windows, one for editing and one for typing commands. When you complete some editing, save the file you are working but don't quit the editor - leave it running for the next lot of editing you need to do. Switch to the other window to issue commands.
Don't forget, the program must be saved in a file called
MyProgram.java.
Compile the program using javac, run it using java.
Ask the demonstrator if you need help.
Have you started to organise your filestore? Where did you save the .java
file?
For each set of exercises it would be a good idea to create and use a
new directory.
Once you have got the program working try editing it to deliberately introduce errors. For example, remove a semi-colon, delete a bracket or change the spelling of one of the words making up the program. Observe the error messages you get when you try to compile the modified program. At first they may not make too much sense but will become familiar! Learn what each error message means and how to resolve the problem reported.
After you have finished experimenting, restore the program to its working condition.
Q1.2 Modify the program in question 1.1 to display the address and phone numbers of the Computer Science Department (hint: look at the web page http://www.cs.ucl.ac.uk/). Use a separate output statement for each line of the address. Don't forget that each output statement should end with a semi-colon.
What happens if you change println to print in the output statements? Try it and see.
You will need to give your program a new name and save it a new file, otherwise you will overwrite your answer to Q1.1.
Q1.3 Copy (cut and paste from the web page version of these exercises) the drawing program code presented in the introduction. Save it into a file - remember how the file should be named? Then compile and run the program. Make sure the line displayed is the same as the one in the picture.
Q1.4 Modify your drawing program to draw a hexagon (6 sides). Don't forget to change the name of the drawing program and save it to a new file, otherwise your answer to 1.3 will get overwritten.
Q1.5 Write a drawing program to draw a rectangle, with top left corner at (20,30) and horizontal sides of length 60 and vertical sides of length 45.
Q1.6 Write a drawing program to draw an equilateral triangle.
Q1.7 Write a drawing program to draw a simple picture of a house. This will need a longer sequence of drawing commands. Don't forget to make use of other drawing shapes such as rectangles.
Q1.8 Write a drawing program to draw a series of circles of increasing size. Use the drawArc for this.
Q1.9 Write a drawing program to display a message consisting of your name and degree programme. Use drawString to do this.
Q1.10 Create a drawing program to draw a bar chart with labels. This will need quite a long list of drawing commands.
Q1.11 Write a drawing program to draw filled shapes using fillRect, fillArc and fillOval. Find out about these by looking at the online Java documentation on class Graphics (http://www.cs.ucl.ac.uk/teaching/java/jdk1.2/docs/index.html)
Q1.12 Write a drawing program to draw a sine wave. A method to compute sin is available in the Java class libraries and is called Math.sin. More information is available in the Java documentation.
Q1.13 Write a drawing program to draw any picture you like using as many features of class Graphics as possible.
Q1.14 Write a drawing program to display the mandelbrot set. Add as many user interface features as you like.